<?php

namespace app\admin\controller\user;

use app\admin\model\UserGroup;
use app\common\model\UserFinanceLog;
use app\common\controller\Backend;
use app\common\library\Auth;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null, $except = true)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        //积分、余额变更
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            $user = $this->model->where('id', $params['id'])->field(['id', 'money', 'score', 'invoice'])->find();
            $this->financeHandle($params, $user);
        }

        $this->view->assign('groupList', build_select('row[group_id]', UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids, true);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /**
     * 用户资产处理
     * @param $params
     * @param $user
     * @return bool
     */
    private function financeHandle($params, $user)
    {
        if (!isset($params['score']) || !isset($params['money']) || !isset($params['invoice'])) {
            return true;
        }
        $data = [];
        if ($user['score'] != $params['score']) {
            $data[] = [
                'user_id' => $params['id'],
                'operator_id' => $this->auth->id,
                'type' => 'score',
                'flag' => $params['score'] > $user['score'] ? 'add' : 'reduce',
                'value' => abs($params['score'] - $user['score']),
                'before' => $user['score'],
                'after' => $params['score'],
                'event' => 'sys',
            ];
        }
        if ($user['money'] != $params['money']) {
            $data[] = [
                'user_id' => $params['id'],
                'operator_id' => $this->auth->id,
                'type' => 'money',
                'flag' => $params['money'] > $user['money'] ? 'add' : 'reduce',
                'value' => abs($params['money'] - $user['money']),
                'before' => $user['money'],
                'after' => $params['money'],
                'event' => 'sys',
            ];
        }
        if ($user['invoice'] != $params['invoice']) {
            $data[] = [
                'user_id' => $params['id'],
                'operator_id' => $this->auth->id,
                'type' => 'invoice',
                'flag' => $params['invoice'] > $user['invoice'] ? 'add' : 'reduce',
                'value' => abs($params['invoice'] - $user['invoice']),
                'before' => $user['invoice'],
                'after' => $params['invoice'],
                'event' => 'sys',
            ];
        }
        if ($data) {
            UserFinanceLog::addRecord($data);
        }
        return true;
    }
}
